//
// Created by Jeffrey Wei on 2022/11/2.
//

import Foundation
import Moya

class NetworkLoggerDefaultPlugin: PluginType {
    // 无法继承,因此采用agent的形式来处理日志
    let agentPlugin: NetworkLoggerPlugin

    init(agentPlugin: NetworkLoggerPlugin) {
        self.agentPlugin = agentPlugin
    }

    convenience init(options: NetworkLoggerPlugin.Configuration.LogOptions = .verbose) {
        var requestNumber = 0
        if options.contains(.requestMethod) { requestNumber += 1 }
        if options.contains(.requestHeaders) { requestNumber += 1 }
        if options.contains(.requestBody) { requestNumber += 1 }
        self.init(agentPlugin: .init(configuration: .init(output: { _, items in
            let isRequestItems = items.count == requestNumber
            let title = isRequestItems ? "请求" : "响应"
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~网络\(title)日志开始~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            for item in items {
                if item.isEmpty == false {
                    print(item, separator: ",", terminator: "\n")
                }
            }
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~网络\(title)日志结束~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        }, logOptions: options)))
    }

    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        agentPlugin.prepare(request, target: target)
    }

    func willSend(_ request: RequestType, target: TargetType) {
        agentPlugin.willSend(request, target: target)
    }

    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        agentPlugin.didReceive(result, target: target)
    }

    func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {
        agentPlugin.process(result, target: target)
    }
}
